package com.iakuil.app.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.iakuil.app.common.core.util.ArrayUtils;
import com.iakuil.app.domain.entity.Author;
import com.iakuil.app.domain.entity.Book;
import com.iakuil.app.repository.dao.AuthorMapper;
import com.iakuil.app.service.AuthorService;
import com.iakuil.app.service.base.CacheableServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 作者 服务实现类
 *
 * @author Kai
 * @since 2023-12-05
 */
@Service
public class AuthorServiceImpl extends CacheableServiceImpl<AuthorMapper, Author> implements AuthorService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIds(Long[] ids) {
        for (Long authorId : ids) {
            this.remove(authorId);
        }

        return super.removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean remove(Long id) {
        // 先删除作者引用
        List<Book> cleared = findRefBooks(id).stream()
            .filter(book -> book.getAuthorIds() != null)
            .peek(entity -> entity.setAuthorIds(ArrayUtils.removeEle(entity.getAuthorIds(), id)))
            .toList();

        // 使用MyBatis Plus提供的Db Kit解决循环依赖问题
        Db.updateBatchById(cleared, 100);

        // 执行真正的删除操作
        return super.remove(id);
    }

    private List<Book> findRefBooks(Long id) {
        // 推荐使用findXxx风格的方法名，以便与通用方法相区分
        return Db.lambdaQuery(Book.class).apply("FIND_IN_SET ('" + id + "', author_ids)").list();
    }
}
